//
//  ESDuanziVC.m
//  Eyeshot
//
//  Created by lanou3g on 15/7/1.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#import "ESDuanziVC.h"
#import "ESDuanziDetailVC.h"
#import "ESCellTopView.h"
#import "ESDuanzi.h"
#import "ESDuanziTableCell.h"
#import "ESToolbar.h"
#import "ESCommentViewController.h"
#import "MJRefresh.h"
#import "ESResponseInfo.h"
#import "UMSocial.h"
#import "ESUserDetailViewController.h"
#define kURL @"http://api.budejie.com/api/api_open.php?a=love&appname=baisishequ&asid=1880212C-B451-4FA7-8DFA-E07254EFCEE9&c=post&client=iphone&device=iPhone%204S&id=14730244&jbk=0&mac=&market=&openudid=5a299ed728ffa000f0c4db0eb49e93d0e3968b2a&sex=m&tj_from=video&udid=&uid=15094656&ver=3.6"
@interface ESDuanziVC ()<ESToolbarDelegate,UMSocialUIDelegate,ESDuanziTableCellDelegate>
@property (nonatomic, strong) NSMutableArray *models;
@property(nonatomic,assign)ESRefreshType refreshType;
@property (nonatomic, strong) ESResponseInfo *responseInfo;
@property(nonatomic,assign)NSInteger page;
@property (nonatomic, strong) ESUserDetailViewController *userDetailVC;
@end

@implementation ESDuanziVC

//进入用户页面详情
- (void)duanZiTableViewCell:(ESDuanziTableCell *)cell didSeletedUserBtn:(ESCellUserProfile *)btn
{
    self.userDetailVC = [[ESUserDetailViewController alloc] init];
    self.userDetailVC.userid = btn.userid;
    [self.navigationController pushViewController:self.userDetailVC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    BOOL night = [[NSUserDefaults standardUserDefaults] boolForKey:@"night"];
    if (night) {
        self.view.backgroundColor = ESColor(50, 50, 50);
    }else{
        self.view.backgroundColor = [UIColor whiteColor];
    }
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _refreshType = ESRefreshNew;
    _page = 0;
    
    [self configTableView];
    [self requestData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(barDidSelect:) name:@"categroyBardidSelect" object:nil];
    
    
   
    
    
}

#pragma mark - 通知响应Action
- (void)barDidSelect:(NSNotification *)notif {
    if ([notif.object integerValue] == 3) {
        [self loadNewData];
        CGFloat footerH = self.tableView.footer.height;
        CGFloat visH = 	SCREEN_HEIGHT - BAR_HEIGHT - CATEGORY_BAR_HEIGHT - footerH;
        [self.tableView scrollRectToVisible:CGRectMake(0, 0, SCREEN_WIDTH, visH) animated:NO];
    }
}

#pragma mark - 配置TableView
- (void)configTableView {
    self.tableView.backgroundColor = ESColor(234, 234, 234);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[ESDuanziTableCell class] forCellReuseIdentifier:@"ESDuanziTableCell"];
    _models = [NSMutableArray array];
    
    __weak ESDuanziVC *wSelf = self;
 
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [wSelf loadNewData];
    }];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [wSelf loadMoreData];
    }];

}

#pragma mark - MJRefresh
- (void)loadNewData {
    _refreshType = ESRefreshNew;
    [self requestData];
    
}

- (void)loadMoreData {
    _refreshType = ESRefreshMore;
    _page+=1;
    
    if (_page < _responseInfo.page) {
        [self requestData];
    }else {
        [self.tableView.footer setTitle:@"" forState:(MJRefreshFooterStateIdle)];
        [self.tableView.footer endRefreshing];
    }
    
    
}


#pragma mark - 网络请求

- (void)requestData {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSString *aType = (_duanziType?_duanziType:@"list");
    
    NSString *maxtime = @"";
    if (_refreshType == ESRefreshMore) {
        maxtime = [NSString stringWithFormat:@"%@",_responseInfo.maxtime];
    }
    NSString *page = [NSString stringWithFormat:@"%ld",_page];
    NSString *reqStr = @"http://api.budejie.com/api/api_open.php";
    
    NSDictionary *reqParas = @{@"a": aType,
                               @"appname": @"baisishequ",
                               @"asid": @"5E6124E7-C271-4F3F-9FE6-33E54108A2F3",
                               @"c": @"data",
                               @"client": @"iphone",
                               @"device": @"iPhone4S",
                               @"from": @"ios",
                               @"jbk": @"0",
                               @"mac": @"",
                               @"market": @"",
                               @"openudid": @"915b9db78a08fe308fdeda8a949ba0f436c6be8f",
                               @"page": page,
                               @"per": @"20",
                               @"sub_flag": @"1",
                               @"type": @"29",
                               @"udid": @"",
                               @"uid": @"15150267",
                               @"ver": @"3.6",
                               @"maxtime":maxtime
                               };
    
    [mgr GET:reqStr parameters:reqParas success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        
        NSDictionary *responseDict = responseObject[@"info"];
        _responseInfo = [ESResponseInfo objectWithKeyValues:responseDict];
        
        NSArray *responseArray = responseObject[@"list"];

        if (_refreshType == ESRefreshNew) {
            [_models removeAllObjects];
        }
        
        for (NSDictionary *dict in responseArray) {
            ESDuanzi *model = [ESDuanzi objectWithKeyValues:dict];
            BOOL isUnique = YES;
            for (ESDuanzi *m in _models) {
                if ([m.ID isEqualToString:model.ID]) {
                    isUnique = NO;
                    break;
                }
            }
            
            if (isUnique) {
                [_models addObject:model];
            }
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ESLog(@"%@",error);
    }];
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [_models count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return [ESDuanziTableCell heightForCellWithModel:_models[indexPath.row]];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ESDuanziTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ESDuanziTableCell" forIndexPath:indexPath];
    cell.model = _models[indexPath.row];
    cell.delegate = self;
    cell.buttomView.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ESCommentViewController *commentVc = [[ESCommentViewController alloc] init];
    commentVc.model = _models[indexPath.row];
    [self.navigationController pushViewController:commentVc animated:YES];
}


#pragma mark - ESToolBar代理
- (void)ESToolbar:(ESToolbar *)toolbar didSelectBtn:(UIButton *)btn {

    switch (btn.tag) {
        case ESToolbarBtnTypeDing:
        {
            NSURL *url = [NSURL URLWithString:kURL];
            NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
            NSOperationQueue *queue = [NSOperationQueue currentQueue];
            [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                
                [btn setImage:[UIImage imageNamed:@"mainCellDingClickN"] forState:(UIControlStateNormal)];
                 NSUInteger count = [btn.titleLabel.text integerValue];
                    NSUInteger newCount = count + 1;
                    NSString *newCon = [NSString stringWithFormat:@"%ld",newCount];
                    [btn setTitle:newCon forState:(UIControlStateNormal)];
                
            }];
        }
            break;
        case ESToolbarBtnTypeCai:
        {
            ESLog(@"2");
        }
            
            break;
        case ESToolbarBtnTypeShare:
        {
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"55955b4c67e58e1c3a000c11"
                                              shareText:@"分享开心从此开始:"
                                             shareImage:[UIImage imageNamed:@"Icon-40"]
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,UMShareToDouban,UMShareToEmail,UMShareToSms,nil]
                                               delegate:self];
        }
            break;
        case ESToolbarBtnTypeComment:
        {
            ESCommentViewController *commentVc = [[ESCommentViewController alloc] init];
            NSIndexPath *indexPath = [self.tableView indexPathForCell:toolbar.parentCell];
            commentVc.model = _models[indexPath.row];
            commentVc.topicType = ESTopicDuanzi;
            [self.navigationController pushViewController:commentVc animated:YES];
            
        }
            break;
            
    }
}


@end


